package com.cauli.account.login.service.impl;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.FIFOCache;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.lang.UUID;
import com.cauli.account.login.model.vo.LoginVerifyImgVO;
import com.cauli.account.login.service.ImgVerifyCodeService;
import com.cauli.utils.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author Cauli
 * @date 2022/12/14 16:21
 * @description 图片验证码 服务实现类
 */
@Service
@Slf4j
public class ImgVerifyCodeServiceImpl implements ImgVerifyCodeService {
    /**
     * 最大容量为 100 的验证码缓存，防止恶意请求占满内存. 验证码有效期为 60 秒.
     */
    private final FIFOCache<String, String> verifyCodeCache = CacheUtil.newFIFOCache(100, 60 * 1000L);

    public LoginVerifyImgVO generatorCaptcha() {
        // 生成验证码和图片
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 45, 4, 7);
        String code = captcha.getCode();
        String imageBase64 = captcha.getImageBase64Data();

        // 通过UUID将验证码写入缓存
        String uuid = UUID.fastUUID().toString();
        verifyCodeCache.put(uuid, code);
        log.info("验证码生成并写入缓存成功->验证码：{}，UUID：{}", code, uuid);

        LoginVerifyImgVO loginVerifyImgVO = new LoginVerifyImgVO();
        loginVerifyImgVO.setUuid(uuid);
        loginVerifyImgVO.setImgBase64(imageBase64);
        return loginVerifyImgVO;
    }

    public void checkCaptcha(String uuid, String code) {
        // 从缓存中获取验证码
        String expectedCode = verifyCodeCache.get(uuid);
        if (!code.equals(expectedCode)) {
            throw new MyException("验证码错误或已失效");
        }
    }
}
